package ca.paulshin.yunatube.http.unused;

import java.io.IOException;
import java.net.Socket;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.net.http.AndroidHttpClient;
import android.util.Log;
import ca.paulshin.yunatube.YunaTubeApplication;

public class YunaTubeHttpClient2 {
	private static final boolean SIMPLE_REPORT = false;
	
	protected HttpResponse get(String url, List<Header> headers, List<NameValuePair> params) {

		HttpClient client = getClient();

		try {
			URI uri = params == null ? new URI(url) : URIUtils.createURI(null, url, -1, null, URLEncodedUtils.format(params, "UTF-8"), null);
			HttpGet httpGet = new HttpGet(uri);
			StringBuilder sb = null;

			if (YunaTubeApplication.debuggable) {
				sb = new StringBuilder("GET ").append(uri.toString());
			}

			if (headers != null) {
				for (Header header : headers) {
					httpGet.addHeader(header);
					if (YunaTubeApplication.debuggable && !SIMPLE_REPORT) {
						sb.append(" [").append(header.getName()).append(":").append(header.getValue()).append("]");
					}
				}
			}
			if (!SIMPLE_REPORT)
				Log.w("YunaTube", sb.toString());

			return client.execute(httpGet);

		} catch (Exception e) {
			if (YunaTubeApplication.debuggable) {
				e.printStackTrace();
			}
			return null;

		} finally {

			if (client instanceof AndroidHttpClient) {
				((AndroidHttpClient) client).close();
			}
		}
	}

	private ClientConnectionManager getClientConnManager() {
		SSLSocketFactory sslFactory = null;
		try {
			sslFactory = new SimpleSSLSocketFactory(null);
		} catch (Exception e) {
			return null;
		}
		sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

		// Enable HTTP parameters
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

		// Register the HTTP and HTTPS Protocols. For HTTPS, register our
		// custom SSL Factory object.
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
		registry.register(new Scheme("https", sslFactory, 443));

		return new ThreadSafeClientConnManager(params, registry);
	}

	private HttpClient getClient() {

		if (android.os.Build.VERSION_CODES.GINGERBREAD <= android.os.Build.VERSION.SDK_INT) {
			return AndroidHttpClient.newInstance("");

		} else {

			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			return new DefaultHttpClient(getClientConnManager(), params);
		}
	}
}

class SimpleSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory {
	private javax.net.ssl.SSLSocketFactory sslFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

	public SimpleSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
		super(null);

		try {
			SSLContext context = SSLContext.getInstance("TLS");

			TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
				@Override
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return new java.security.cert.X509Certificate[] {};
				}

				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}
			} };

			context.init(null, trustAllCerts, new SecureRandom());
			sslFactory = context.getSocketFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
		return sslFactory.createSocket(socket, host, port, autoClose);
	}

	@Override
	public Socket createSocket() throws IOException {
		return sslFactory.createSocket();
	}
}